package coffeenc.mall.admin.controller;

import coffeenc.mall.common.api.CommonResult;
import coffeenc.mall.admin.dto.UmsAdminLoginParam;
import coffeenc.mall.admin.dto.UmsAdminRegisterParam;
import coffeenc.mall.admin.entity.UmsAdmin;
import coffeenc.mall.admin.service.UmsAdminService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Api(tags = "UmsAdminController", description = "后台用户管理")
public class UmsAdminController {

    @Value("${jwt.tokenHeaderKey}")
    private String tokenHeaderKey;
    @Autowired
    private UmsAdminService umsAdminService;

    @ApiOperation("用户注册")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ApiImplicitParam(name = "umsAdminParam",value = "用户注册参数")
    public CommonResult register(@Validated @RequestBody UmsAdminRegisterParam umsAdminRegisterParam){
        UmsAdmin umsAdmin = umsAdminService.register(umsAdminRegisterParam);
        if (umsAdmin == null)
            return CommonResult.failed();
        return CommonResult.success(umsAdmin);
    }

    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CommonResult login(@Validated @RequestBody UmsAdminLoginParam umsAdminLoginParam){
        String token = umsAdminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token==null)
            return CommonResult.failed("账户不存在或密码错误");
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHeader", tokenHeaderKey);
        tokenMap.put("token",token);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("默认测试接口")
    @RequestMapping(method = RequestMethod.GET,value = "/test")
    public CommonResult test(){
        return CommonResult.failed("default api for testing");
    }
}
